package com.example.xd.default_call.fragment

import android.content.Context
import android.graphics.ImageFormat
import android.hardware.Camera
import android.hardware.camera2.CameraManager
import android.os.Handler
import android.os.Message
import android.telecom.Call
import android.telecom.InCallService
import android.telecom.VideoProfile
import android.view.SurfaceHolder
import android.view.View
import com.example.xd.default_call.R
import com.example.xd.default_call.TimeFormatUtil
import com.example.xd.default_call.eventbus_msg.IsSlienceMsg
import com.example.xd.default_call.eventbus_msg.VideoCallInMsg
import kotlinx.android.synthetic.main.fragment_call_video_in.*
import kotlinx.android.synthetic.main.fragment_call_video_out.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @auther XuDan on 2020/8/13.
 */
class Call_Video_In_Fragment : BaseFragment(), View.OnClickListener, SurfaceHolder.Callback {

    var time: Long = 0
    var mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                time++
                video_in_time_tv.setText("通话时长：" + TimeFormatUtil.instance.stringForTime(time))
                val obtain = Message.obtain()
                obtain.what = 1
                sendMessageDelayed(obtain, 1000)
            }
        }
    }

    override fun registerMethod() {
        EventBus.getDefault().register(this)
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_call_video_in

    }

    override fun initViews(view: View) {
        video_in_connect_img.setOnClickListener(this)
        video_in_cut_img.setOnClickListener(this)
        video_in_tv_change.setOnClickListener(this)
        video_in_tv_keyboard.setOnClickListener(this)
        video_in_change_img.setOnClickListener(this)
        video_in_float_img.setOnClickListener(this)
        video_in_silence_img.setOnClickListener(this)
        video_in_close_img.setOnClickListener(this)
        video_in_remote_sv.holder.addCallback(this)
    }

    var isSlience = false
    override fun onClick(v: View) {
        when (v) {
            video_in_connect_img -> {
                call.answer(VideoProfile.STATE_BIDIRECTIONAL)
            }
            video_in_cut_img -> {
                call.disconnect()
                videoCall?.unregisterCallback(videoCallBack)
                mActivity.finish()
            }
            video_in_tv_change -> {
            }
            video_in_tv_keyboard -> {
            }
            video_in_change_img -> {
            }
            video_in_float_img -> {
            }
            video_in_silence_img -> {
                isSlience = !isSlience
                EventBus.getDefault().post(IsSlienceMsg(isSlience))
            }
            video_in_close_img -> {
            }
        }
    }

    lateinit var myCallBack: MyCallBack
    lateinit var call: Call

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun videocallInStart(msg: VideoCallInMsg) {
        call = msg.call
        myCallBack = MyCallBack()
        call.registerCallback(myCallBack)
    }

    override fun unRegisterMethod() {
        call.unregisterCallback(myCallBack)
        videoCall?.unregisterCallback(videoCallBack)
        EventBus.getDefault().unregister(this)
    }

    var videoCall: InCallService.VideoCall? = null
    lateinit var videoCallBack: MyVideoCallBack
    lateinit var cameraManager: CameraManager


    inner class MyCallBack : Call.Callback() {
        override fun onStateChanged(call: Call, state: Int) {
            super.onStateChanged(call, state)
            when (state) {
                Call.STATE_ACTIVE -> {
                    val obtain = Message.obtain()
                    obtain.what = 1
                    mHandler.sendMessage(obtain)
                    cameraManager =
                        mActivity.getSystemService(Context.CAMERA_SERVICE) as CameraManager
                    videoCall = call.videoCall
                    videoCallBack = MyVideoCallBack()
                    videoCall?.registerCallback(videoCallBack)
                    videoCall?.setCamera(cameraManager.cameraIdList[1])//默认后置
                    videoCall?.setDeviceOrientation(0)
                    videoCall?.setDisplaySurface(video_in_remote_sv.holder.surface)//显示远程接收视频
                    videoCall?.setPreviewSurface(video_in_my_sv.holder.surface)//用户当前捕获的预览
                    videoCall?.requestCallDataUsage()
                    videoCall?.requestCameraCapabilities()
                }
                Call.STATE_DISCONNECTED -> {
                    video_in_time_tv.text = "通话结束"
                    mHandler.removeCallbacksAndMessages(null)
                    mActivity.finish()
                }
            }
        }
    }

    inner class MyVideoCallBack : InCallService.VideoCall.Callback() {
        override fun onVideoQualityChanged(videoQuality: Int) {//处理视频质量的更改
        }

        override fun onCallDataUsageChanged(dataUsage: Long) {//处理当前视频会话使用的总数据的更新
        }

        override fun onPeerDimensionsChanged(width: Int, height: Int) {//处理来自对等设备的视频尺寸更改
        }

        override fun onSessionModifyResponseReceived(
            status: Int,
            requestedProfile: VideoProfile?,
            responseProfile: VideoProfile?
        ) {//当Connection.VideoProvider接收到对先前发送给对等设备的会话修改请求的响应时调用
        }

        override fun onSessionModifyRequestReceived(videoProfile: VideoProfile?) {//在Connection.VideoProvider接收到来自对等设备的会话修改请求时调用
        }

        override fun onCameraCapabilitiesChanged(cameraCapabilities: VideoProfile.CameraCapabilities?) {//处理当前所选摄像机功能的更改
        }

        override fun onCallSessionEvent(event: Int) {
        }

    }


    override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
    }

    override fun surfaceDestroyed(holder: SurfaceHolder?) {
        camera!!.stopPreview()
        camera!!.release()
        camera = null
    }


    var camera: Camera? = null
    override fun surfaceCreated(holder: SurfaceHolder?) {
        camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
        camera!!.setDisplayOrientation(90)
        camera!!.setPreviewDisplay(holder)
        val parameters = camera!!.parameters
        parameters.setPictureSize(1920, 1080)
        parameters.previewFormat = ImageFormat.NV21
        camera!!.parameters = parameters
        camera!!.startPreview()
    }
}